import React, {useRef,useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from "@ant-design/pro-table";
import {Select, Button, Tooltip, Switch, Drawer, Tree, Modal, Form,message} from 'antd';
import {DeleteOutlined,FileOutlined} from '@ant-design/icons';
import {fetchDocsList,fetchCurrentDocs,getArticleDetail,switchDocs,deleteDocs} from '@/services/docs'
import ProForm, {ProFormText} from "@ant-design/pro-form";
import { Checkbox, Divider } from 'antd';

const CheckboxGroup = Checkbox.Group;


const { DirectoryTree } = Tree;
const { Option } = Select;

const Index = () => {
  const ref = useRef();

  // 查看文档模态框
  const [visible, setVisible] = useState(false);

  // 显示文章的模态框
  const [isArticleModal,setIsArticleModal] = useState(false);

  // 设置当前选中的版本version
  const [currentVersion,setCurrentVersion] = useState(1);


  // 表单的初始值
  const [initialValues,setInitialValues] = useState();

  // 文本框输入的md数据
  const [vditorMdData,setVditorMdData] = useState(undefined);

  // 文本框输入的html数据
  const [vditorHtmlData,setVditorHtmlData] = useState(undefined);

  // 显示 删除的模态框
  const [isModal,setIsModal] = useState(false)

  // // 删除模态框全选和选择的复选框
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);




  // 关闭
  const onClose = () => {
    setVisible(false);
  };

  // 目录数据 设置状态
  const [treeData,setTreeData] = useState(undefined);

  const [version,setVersion] =useState()
  // 获取列表数据
  const getDocsList = async () => {
    const response = await fetchDocsList()
    const ver = response.data.map(item => {
      return {
        id:item.id,
        version:item.version
      }
    })
    setVersion(ver)
    return {
      data: response.data
    }
  }

  // 删除文章
  const isDeleteArticle = async (id) => {
    const data = {
      type:"summary",
      id,
    }
    const response = await deleteDocs(data);
    if (response.status === undefined) {
      message.success('删除成功')
      ref.current.reload()
    }
  }

  // 查看目录
  const lookDocs = async (did) =>{
    setVisible(true)
    const data = {
      id:did,
      version:currentVersion
    }
    const response = await fetchCurrentDocs(data);
    const res = response.docs_summaries.map(item => {
      return {
        title: item.title,
        key:item.id,
        selectable:false,
        children: item.child.map(citem => {
        return {
          title: citem.title,
          key:citem.id,
          selectable:true,
          icon: <FileOutlined />,
        }
        })
      }
    })
    setTreeData(res)
  }

  // 获取当前版本的id 改变状态
  const getCurrentVersion = (id) =>{
    setCurrentVersion(id)
  }

  // 点击文章 打开模态框 获取文章详情
  const onSelect = async  (keys) => {
    setIsArticleModal(true)
    // 文章详情 keys文章详情的id
    const response = await getArticleDetail(keys[0]);
    setVditorMdData(response.article_md)
    setVditorHtmlData(response.article)
    setInitialValues(response.data)
  };

  const switchStatus = async (id) => {
    const response = await switchDocs({type:"docs",id})
    if (response.status === undefined) {
      ref.current.reload()
      message.success('更改状态成功')
    }
  }
  //
  // const versionStatus = async (id) => {
  //   const response = await switchDocs({type:"version",id})
  //   if (response.status === undefined) {
  //     ref.current.reload()
  //     message.success('更改状态成功')
  //   }
  // }

  const switchHot = async (id) => {
    const response = await switchDocs({type:"docsHot",id})
    if (response.status === undefined) {
      ref.current.reload()
      message.success('热门状态改变成功')
    }
  }

  const [plainOptions,setDataVersion] = useState(undefined);

  // 删除文档 或者删除文档下面的版本
  const [uid,setUid] = useState(undefined);
  const isDelete = async (show,id) => {
    setIsModal(show)
    const a = version.filter(item => {
      if (id === item.id) {
        return item
      }
    })
    // setDataVersion(a[0].version.data)
    const aa = a[0].version.data.map(item => {
      return {
        label:item.version,
        value: item.id,
        disabled:false,
      }
    })
    setDataVersion(aa)
    setUid(id)
  }


  const [dataList,setDataList] = useState(undefined);

  const onChange = list => {
    setDataList(list)
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };

  const onCheckAllChange = e => {
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  const onSubmit =async () => {
    const data = {
      docs_id:uid,
      id:dataList,
      type:"version"
    }
    const response =await deleteDocs(data)
    if (response.status === undefined) {
      ref.current.reload()
      message.success("删除成功")
    }
  }

  // 字段
  const columns = [
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '副标题',
      dataIndex: 'subtitle',
      ellipsis:true
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_,record) => {
        return  <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={() => switchStatus(record.id) }
          defaultChecked={record.status === 0 ? false:true} />
      }
    },
    {
      title: '是否热门',
      dataIndex: '',
      render: (_,record) =>{
        return (<Switch
          checkedChildren="热门"
          unCheckedChildren="上热门"
          onChange={() => {switchHot(record.id)}}
          defaultChecked
        />)
      }
    },
    {
      title: '类型',
      dataIndex: 'difficulty'
    },
    {
      title: '版本',
      dataIndex: 'default_versions',
      render: (_, record) => {
        return <Select
          defaultValue={currentVersion}
          style={{ width: 120 }} onChange={(id) =>{getCurrentVersion(id)}}>
          {
            record.version.data.map(item => {
              return (<Option key={item.id} value={item.id}>&nbsp;&nbsp;{item.version}
              </Option>)
            })
          }
        </Select>
      }
    },
    {
      title: '查看文档',
      render: (_,record) =>{
        return <Tooltip title="查看文档">
          <a onClick={() => {lookDocs(record.id)}}>查看文档</a>
        </Tooltip>
      }
    },
    {
      title: '编辑',
      render: (_,record) => {
        return <div>
          &nbsp;&nbsp;
          <Button
            type="danger"
            shape="circle"
            icon={<DeleteOutlined/>}
            onClick={() => isDelete(true,record.id)} />
        </div>

      }
    },
  ]

  return (
    <PageContainer>
      <ProTable
        actionRef={ref}
        columns={columns}
        request={async (params = {}, success, total) =>
          getDocsList(params, success, total)}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        checkStrictly={false}
        search={false}
        pagination={false}
        ellipsis={true}
        dateFormatter="string"
        headerTitle="文档列表"
      />
      <Drawer
        title="目录列表"
        placement="right"
        closable={false}
        onClose={onClose}
        visible={visible}
        destroyOnClose={true}
      >
        <DirectoryTree
          multiple={true}
          defaultExpandAll
          onSelect={onSelect}
          treeData={treeData}
          expandAction="click"
        />
      </Drawer>
      <Modal
        title="文章内容"
        visible={isArticleModal}
        onCancel={() => {setIsArticleModal(false)}}
        footer={true}
      >
        <Button onClick={() => isDeleteArticle(initialValues.id)}>删除该文章</Button>
        {
          initialValues === undefined ? '' : <ProForm
            initialValues={initialValues}
            onFinish={() => {}}
            submitter={{
              searchConfig: {
                submitText: '删除',
              },
              submitButtonProps: {
                size: 'middle',
                style: {
                  width: '100%',
                },
              },
            }}
          >
            <ProFormText
              width="100"
              name="title"
              label="文章标题"
              rules={[
                {
                  required: true,
                  message: '请输入文章标题',
                },
                {
                  min:10,
                  message: '请输入文章标题 最少10个字符',
                },
                {
                  max:100,
                  message: '文章标题最多100个字符',
                },
              ]}
            />
            {
              vditorMdData === undefined ? '':
                <div>{vditorMdData} {vditorHtmlData}</div>
            }
          </ProForm>
        }
      </Modal>

      <Modal
        title="选择要删除的版本"
        visible={isModal}
        onCancel={() => setIsModal(false)}
        footer={false}
        destroyOnClose={true}
      >
        <ProForm
          initialValues={initialValues}
          onFinish={(a) => onSubmit(a)}
          submitter={{
            searchConfig: {
              submitText: '删除',
            },
            submitButtonProps: {
              size: 'middle',
              style: {
                width: '100%',
              },
            },
          }}
        >
          <Form.Item name="version" label="全选">
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <Divider />
            <CheckboxGroup options={plainOptions} onChange={onChange} />
          </Form.Item>
        </ProForm>
      </Modal>
    </PageContainer>
  );
};

export default Index;
